/**
 * Namespace that holds page handlers
 */
var Pages = {
	/**
	 * Main page
	 */
	'main' : {
		/**
		 * Check if this is a main page
		 *
		 * @returns {Boolean} "true" if this is a main page
		 */
		check : function() {
			return $('#mob, #contentselect').size() == 2;
		},
		
		/**
		 * "ready" state handler
		 */
		ready : function() {
			switch (bot.getCurrentMode()) {
				// Go to quests page
				case 'questComplete':
					$('#contentselect').val(5).change();
					break;
				// Select new quest mob
				case 'setNewMob':
					$('#mob').val($('#mob option[style]').val()).change();
					
					bot.setMode('battle');
					this.ready();
					
					break;
				// Default ("battle") mode
				default:
					var $btn = $('#battlebutton');
			
					$btn.size() && $btn[0].click();
			}
		}
	},
	
	/**
	 * ReCaptcha page
	 */
	'captcha' : {
		/**
		 * Check if this is a ReCaptcha page
		 *
		 * @returns {Boolean} "true" if this is a ReCaptcha page
		 */
		check : function() {
			return $('#recaptcha_div').size();
		},
		
		/**
		 * "loaded" state handler
		 */
		loaded : function() {
			bot.log('ReCaptcha');
			
			if (webkitNotifications.checkPermission() == 0) {
				webkitNotifications.createNotification('', 'TLR Bot', 'Check the ReCaptcha').show();
			}
		}
	},

	/**
	 * Battle page
	 */
	'battle' : {
		/**
		 * Check if this is a battle page
		 *
		 * @returns {Boolean} "true" if this is a battle page
		 */
		check : function() {
			return $('#battlebutton').val() == 'Battle Again';
		},
		
		/**
		 * "loaded" state handler
		 */
		loaded : function() {
			this.checkResults();
			this.checkLevelUp();
			this.checkLoot();
			this.checkQuestComplete();
			this.checkDungeonComplete();
		},
		
		/**
		 * "ready" state handler
		 */
		ready : function() {
			if (bot.getCurrentMode() == 'battle') {
				$('#battlebutton')[0].click();
			}
			else {
				$('input[value="Continue"]', $content)[0].click();
			}
		},
		
		/**
		 * Check battle results (win or defeat)
		 */
		checkResults : function() {
			bot.setStat($('span:contains("You defeated the")', $content).size() ? 'lineage-wins' : 'lineage-defeats', 1);
			
			var percentage = 0;
			
			if ($('#lineage-wins').text() != '0') {
				percentage = parseInt(100 - $('#lineage-defeats').text().replace(/\D/g, '') / $('#lineage-wins').text().replace(/\D/g, '') * 100);
			}
			
			$('#lineage-win-percentage').text(percentage + '%');
		},
		
		/**
		 * Check for levelup (and also for rune shards gift for that)
		 */
		checkLevelUp : function() {
			var $levelup = $(':contains("You gained a level")', $content);
			
			if (!$levelup.size()) {
				return false;
			}
			
			bot.setStat('lineage-levels', 1);
			
			// If some rune shards found
			$levelup.is(':contains("rune shard(s)")') && bot.setStat('loot-main-shards', $levelup.text().replace(/[^\d+]/g, ''));
		},
		
		/**
		 * Check for the loot
		 */
		checkLoot : function() {
			var $loot = $('#drop');
			
			if (!$loot.size()) {
				return;
			}
			
			var details = $('img:first', $loot).attr('src').split('/'),
				lootText = $loot.text(),
				lootType = details[2],
				statsMap = ['', 'health', 'attack', 'defence', 'accuracy', 'evasion', 'luck'],
				runesMap = ['', 'minor', 'major', 'ancient'],
				runeLevelMap = ['', 'common', 'uncommon', 'rare', 'legendary', 'epic', 'supreme'];
			
			bot.log('loot', lootText);
			console.dir($loot);
			
			// Do actions depending of loot type
			switch (details[2]) {
				// Stats up
				case 'stats':
					bot.setStat('main-' + statsMap[parseInt(details[3])], 1);
					break;
				// Rune found
				case 'runes':
					bot.setStat('loot-runes-' + runesMap[details[3]] + '-' + runeLevelMap[parseInt(details[4])], 1);
					break;
				// Key found
				case 'keys':
					bot.setStat('loot-keys-' + ['', '', 'green', 'blue', 'yellow', 'purple', 'red'][parseInt(details[3])], 1);
					break;
				// Other loot (shards, etc.)
				// We will define loot type and proceed to default step
				case '.png':
					////////////////// You found a tiny source of 4 rune shards! (8 Class Bonus)
					(lootText.indexOf('rune shards') >= 0) && (lootType = 'shards');
				// Main loot found or something else
				default:
					var pattern = /[\d\,]+/g,
						value = 0,
						match;
					
					while (match = pattern.exec(lootText)) {
						value += +match.toString().replace(/\D/g, '');
					}
					
					bot.setStat('loot-main-' + lootType, value);
			}
		},
		
		/**
		 * Check if quest is completed
		 */
		checkQuestComplete : function() {
			if ($(':contains("You have completed the quest")', $content).size()) {
				bot
					.log('quest', 'Quest complete')
					.setMode('questComplete');
			}
		},
		
		/**
		 * Check if dungeon is completed
		 * Because of mob selector is being reset, we need to set the current quest mob manually
		 */
		checkDungeonComplete : function() {
			var $success = $('.success', $content);
			
			if ($success.is(':contains("You have found the treasure")')) {
				bot
					.log('dungeon', $success.text())
					.setMode('setNewMob')
					.setStat('lineage-dungeons', 1);
			}
		}
	},
	
	/**
	 * Quests page
	 */
	'quests' : {
		check : function() {
			return $('#contentselect').val() == 5;
		},
		
		loaded : function() {
			var $success = $('.success', $content);
			
			if ($success.size()) {
				bot.setStat('lineage-quests', 1);
				bot.log('quest', $success.text());
			}
		},
		
		ready : function() {
			var $btn;
			
			if (($btn = $('input[value="Collect Reward From Quest"]', $content)) && $btn.size()) {
				$btn[0].click();
			}
			else if (($btn = $('input[value="Generate Quest"]', $content)) && $btn.size()) {
				$btn[0].click();
			}
			else {
				bot.setMode('setNewMob');
				
				$('#contentselect').val(1).change();
			}
		}
	},
	
	/**
	 * Tradeskills page
	 */
	'tradeskills' : {
		counter : 0,
		
		check : function() {
			return $('#contentselect').val() == 4;
		},
		
		ready : function() {
			var $link = $('a:contains("for 10 seconds")', $content);
			
			if ($link.size()) {
				bot.proxyCallRaw($link.attr('href'));
			}
			else {
				if (this.counter++ % 2) {
					this.checkResults();
				}
			}
		},
		
		checkResults : function() {
			var self = this,
				$link = $('a:contains("Continue")', $content);
			
			if (!$link.size()) {
				setTimeout(function() {
					self.checkResults();
				}, 200);
			
				return this;
			}
			
			// * Your Mining level has increased to 37! *
			// Search if mastery increased
			var pattern = /Your (\w+) level has increased/g,
				result = $('#tsdiv').text(),
				match;
			
			while (match = pattern.exec(result)) {
				bot.setStat('ts-mastery-' + match[1].toLowerCase(), 1);
			}
			
			// Search if ingots found
			var pattern = /You gained a total of ([\d\,]+) (\w+)/,
				results = $('#tsdiv').text();
			
			results = pattern.exec(results);
			
			bot
				.proxyCallRaw($link.attr('href'))
				.setStat('loot-ts-ingots', $(':contains("ingot")', '#tsdiv').size())
				.setStat('loot-ts-' + results[2].toLowerCase(), results[1].replace(/\D/, ''));
		}
	},
	
	/**
	 * Arena page
	 */
	'arena' : {
		check : function() {
			return $('#contentselect').val() == 10;
		},
		
		loaded : function() {
			if ($('.success', $content).size()) {
				bot.setNewArenaTime();
				bot.log('arena', 'Entered new arena');
				bot.setMode('battle');
			}
		},
		
		ready : function() {
			if (bot.getCurrentMode() == 'newArena') {
				$('a:contains("Join"):eq(1)')[0].click();
			}
			else {
				$('#contentselect').val(1).change();
			}
		}
	}
};